{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#使用多线程：在携程中集成阻塞io\n",
    "import asyncio\n",
    "from concurrent.futures import ThreadPoolExecutor\n",
    "import socket\n",
    "from urllib.parse import urlparse\n",
    "\n",
    "\n",
    "def get_url(url):\n",
    "    #通过socket请求html\n",
    "    url = urlparse(url)\n",
    "    host = url.netloc\n",
    "    path = url.path\n",
    "    if path == \"\":\n",
    "        path = \"/\"\n",
    "\n",
    "    #建立socket连接\n",
    "    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
    "    # client.setblocking(False)\n",
    "    client.connect((host, 80)) #阻塞不会消耗cpu\n",
    "\n",
    "    #不停的询问连接是否建立好， 需要while循环不停的去检查状态\n",
    "    #做计算任务或者再次发起其他的连接请求\n",
    "\n",
    "    client.send(\"GET {} HTTP/1.1\\r\\nHost:{}\\r\\nConnection:close\\r\\n\\r\\n\".format(path, host).encode(\"utf8\"))\n",
    "\n",
    "    data = b\"\"\n",
    "    while True:\n",
    "        d = client.recv(1024)\n",
    "        if d:\n",
    "            data += d\n",
    "        else:\n",
    "            break\n",
    "\n",
    "    data = data.decode(\"utf8\")\n",
    "    html_data = data.split(\"\\r\\n\\r\\n\")[1]\n",
    "    print(html_data)\n",
    "    client.close()\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import time\n",
    "    start_time = time.time()\n",
    "    loop = asyncio.get_event_loop()\n",
    "    executor = ThreadPoolExecutor(3)\n",
    "    tasks = []\n",
    "    for url in range(20):\n",
    "        url = \"http://shop.projectsedu.com/goods/{}/\".format(url)\n",
    "        task = loop.run_in_executor(executor, get_url, url)\n",
    "        tasks.append(task)\n",
    "    loop.run_until_complete(asyncio.wait(tasks))\n",
    "    print(\"last time:{}\".format(time.time()-start_time))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
